package com.dao.impl;

import com.util.HibernateUtil;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;

import com.dao.TargetDAO;
import com.rev.Action;
import com.rev.Sourcetype;
import com.rev.Target;
import com.rev.TargetHome;
import com.rev.TargettypeHome;

public class TargetDAOImpl implements TargetDAO{
	private TargetHome th = new TargetHome(); 
	private TargettypeHome tth = new TargettypeHome(); 
	public boolean insert(Target target) {
		try {
			Session session = HibernateUtil.getSessionFactory().openSession();
			Transaction  transaction = session.beginTransaction();
			if(tth.findById(target.getTargettype().getIdtargetType())== null)
				tth.attachDirty(target.getTargettype());
			th.attachDirty(target);
			transaction.commit();
			session.close();
			return true;
		} catch (Exception e) {}
		return false;
	}

	public boolean update(Target target) {
		try {
			Session session = HibernateUtil.getSessionFactory().openSession();
			Transaction  transaction = session.beginTransaction();
			th.attachDirty(target);
			transaction.commit();
			session.close();
			return true;
		} catch (Exception e) {
			// TODO: handle exception
		}
		return false;
	}

	public boolean delete(Target target) {
		try {
			Session session = HibernateUtil.getSessionFactory().openSession();
			Transaction  transaction = session.beginTransaction();
			th.delete(target);
			transaction.commit();
			session.close();
			return true;
		} catch (Exception e) {
			// TODO: handle exception
		}
		return false;
	}

	public Target findById(int id) {
		try {
			Session session = HibernateUtil.getSessionFactory().openSession();
			session.beginTransaction();
			Target s = th.findById(id);
			session.getTransaction().commit();
			session.close();
			return s;
		} catch (Exception e) {
			// TODO: handle exception
		}
		return null;
	}

	public List<Action> findActions(Target target) {
		// TODO Auto-generated method stub
		return null;
	}
	public List<Target> findAll() {

		try {
			Session session = HibernateUtil.getSessionFactory().openSession();
			session.beginTransaction();
			List list = th.findByExample(new Target());
			session.getTransaction().commit();
			session.close();
			return list;
		} catch (Exception e) {
		}
		return null;
	}
}
